/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ebookmgr;

import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 *
 * @author mazhao
 */
public class EBookMgrUtil {

    /**
     * Show Error Message OptionPane and Exit!
     * @param msg Message on OptionPane!
     */
    public static void showMessageAndExit(String msg) {
        JOptionPane.showMessageDialog(null, msg);
        System.exit(0);
    }

    /**
     * Put me in parent's center.
     * @param parent parent container always a JFrame
     * @param me put container always a JDialog
     * @return proper position.
     */
    public static Point getProperPosition(Container parent, Container me) {
        int pwidth = parent.getWidth();
        int pheight = parent.getHeight();

        int mwidth = me.getWidth();
        int mheight = me.getHeight();

        int relativeWidth = (pwidth - mwidth) / 2;
        int relativeHeight = (pheight - mheight) / 2;

        int x = parent.getX() + relativeWidth;
        int y = parent.getY() + relativeHeight;

        return new Point(x, y);
    }

    /**
     * Set JFrame cetner of the screen.
     * @param frame target frame
     */
    public static void setJFrameCenter(JFrame frame) {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

        int x = (int) ((screenSize.getWidth() - frame.getWidth()) / 2);
        int y = (int) ((screenSize.getHeight() - frame.getHeight()) / 2);

        frame.setLocation(x, y);
        
    }


    /**
     * Get OS Name.
     * @return OS Name.
     */
    public static String getOSName() {
        return System.getProperty("os.name");
    }

    /**
     * is on mac?
     * @return true on mac, false else
     */
    public static boolean isMac() {
        return getOSName().startsWith("Mac");
    }

    /**
     * is on linux
     * @return true on linux, false else
     */
    public static boolean isLinux() {
        return getOSName().startsWith("Linux");
    }

    /**
     * is on windows
     * @return true on windows, false else
     */
    public static boolean isWindows() {
        return getOSName().startsWith("Windows");
    }


    /**
     * get file separator.
     * windows: \
     * Mac, Linux, Unix: /
     * @return
     */
    public static String getFileSeparator() {
        return System.getProperty("file.separator");
    }

    /**
     * get line separator
     * windows: \r\n
     * linux: \n
     * mac: \r
     * @return
     */
    public static String getLineSeparator() {
        return System.getProperty("line.separator");
    }

    /**
     * safely close writer.
     * @param w writer
     */
    public static void safelyClose(Writer w) {
        if(w != null) {
            try {
                w.flush();
                w.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    public static void safelyClose(OutputStream os) {
        if(os != null) {
            try {
                os.flush();
                os.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * safely close reader
     * @param r reader
     */
    public static void safelyClose(Reader r) {
        if(r != null) {
            try {
                r.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    public static void safelyClose(InputStream is) {
        if(is != null) {
            try {
                is.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    /**
     * create icon for label, button or menu item.
     * @param path image path (relative to current java file)
     * @return ImageIcon
     */
    public static ImageIcon createIcon(String path) {
        URL frameurl = EBookMgrUtil.class.getResource(path);
        ImageIcon icon = new ImageIcon(frameurl);
        return icon;
    }

    public static File[] listAllFiles(String folder, boolean recursive) {
        List<File> allFiles = new ArrayList<File>();

        File root = new File(folder);

        // if this is a file, add and return
        if (root.isFile()) {
            allFiles.add(new File(folder));
            // if this is a folder
        } else {
            // list all files
            File[] files = root.listFiles(new FileFilter() {

                @Override
                public boolean accept(File pathname) {
                    return pathname.isFile();
                }
            });

            if (files != null && files.length > 0) {
                // if is ebook, add
                for (File curFile : files) {
                    allFiles.add(curFile);
                }

            }

            if (recursive) {
                // list all folders
                File[] folders = root.listFiles(new FileFilter() {

                    @Override
                    public boolean accept(File pathname) {
                        return pathname.isDirectory();
                    }
                });

                if (folders != null && folders.length > 0) {
                    // each invoke findFiles recursively.
                    for (File curFolder : folders) {
                        // recursively!!!
                        File[] filesInThisFolder = listAllFiles(curFolder.getAbsolutePath(), recursive);
                        List<File> tempFiles = Arrays.asList(filesInThisFolder);
                        allFiles.addAll(tempFiles);
                    }
                }
            }
        }

        return allFiles.toArray(new File[allFiles.size()]);
    }

    public static final String byteToKM(long size) {
        String suffix = "K";
        double d = size / 1024.0;
        if(d > 1024.0) {
            d = d / 1024.0;
            suffix = "M";
        }
        String prefix = "" + d;
        // one digital after point
        prefix = prefix.substring(0, prefix.indexOf(".") + 2);
        return prefix + suffix;
    }


    

    private Image getScaledImage(Image srcImg, int w, int h) {
        BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = resizedImg.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2.drawImage(srcImg, 0, 0, w, h, null);
        g2.dispose();
        return resizedImg;
    }
}
